<template>
	<div>
		<el-form :inline="true">
			<el-form-item>
				<el-input
						v-model="searchForm.name"
						placeholder="姓名"
						clearable
						style="margin-right:10px; width:30%"
				>
				</el-input>

				<el-input
						v-model="searchForm.lesson"
						placeholder="教授课程"
						clearable
						style="margin-right:10px; width:30%"
				>
				</el-input>
			</el-form-item>

			<el-form-item>
				<el-button @click="getPersonTrainList">搜索</el-button>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="addHandle" v-if="hasAuth('sys:personTrain:save')">新增</el-button>
			</el-form-item>
			<el-form-item>
				<el-popconfirm title="确定批量删除吗？" @confirm="delHandle(null)">
					<el-button type="danger" slot="reference" v-if="hasAuth('sys:personTrain:delete')">批量删除</el-button>
				</el-popconfirm>
			</el-form-item>
		</el-form>

		<el-table
				ref="multipleTable"
				:data="tableData"
				tooltip-effect="dark"
				style="width: 100%"
				border
				stripe
				@selection-change="handleSelectionChange">

			<el-table-column
					type="selection"
					width="55">
			</el-table-column>

			<el-table-column
					prop="name"
					label="姓名"
					width="80">
			</el-table-column>

			<el-table-column
					prop="photo"
					label="照片"
					width="120">
				<template slot-scope="scope">
				<el-image
					style="width: 100px; height: 100px"
					:src="scope.row.photo"
					:fit="fit"
					:preview-src-list="scope.row.photo">
					>
				</el-image>
				</template>
			</el-table-column>
		
			<el-table-column
					prop="sex"
					label="性别">
			</el-table-column>

			<el-table-column
					prop="phone"
					label="电话号码">
			</el-table-column>

			<el-table-column
					prop="lesson"
					label="教授课程">
			</el-table-column>

			<el-table-column
					prop="lessonStartTime"
					width="110"
					label="课程开始时间"
					:formatter="formatDateTime"
					>
			</el-table-column>

			<el-table-column
					prop="lessonEndTime"
					width="110"
					label="课程结束时间"
					:formatter="formatDateTime"
					>
			</el-table-column>

			<el-table-column
					prop="introduction"
					label="个人介绍">
			</el-table-column>

			<el-table-column
					prop="sysBookingVos"
					width="320"
					label="预约信息"
					>
					<template slot-scope="scope">
						<el-tag size="small" type="info" v-for="item in scope.row.sysBookingVos" :key="item">{{item.username}}:{{item.startTime}}-{{item.endTime}}</el-tag>
					</template>
			</el-table-column>

			<el-table-column
					prop="icon"
					width="200px"
					label="操作">

				<template slot-scope="scope">
					<el-button type="text" @click="editHandle(scope.row.id)"  v-if="hasAuth('sys:personTrain:update')">编辑</el-button>
					<el-divider direction="vertical" v-if="hasAuth('sys:personTrain:update')"></el-divider>

					<template>
						<el-popconfirm title="确定删除这个私人教练吗？" @confirm="delHandle(scope.row.id)">
							<el-button type="text" slot="reference"  v-if="hasAuth('sys:personTrain:delete')">删除</el-button>
						</el-popconfirm>
					</template>
				</template>
			</el-table-column>

		</el-table>

		<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper"
				:page-sizes="[10, 20, 50, 100]"
				:current-page="current"
				:page-size="size"
				:total="total">
		</el-pagination>


		<!--新增对话框-->
		<el-dialog
				title="提示"
				:visible.sync="dialogVisible"
				width="600px"
				:before-close="handleClose">

			<el-form :model="editForm" :rules="editFormRules" ref="editForm">
				<el-form-item label="姓名" prop="name" label-width="150px">
					<el-input v-model="editForm.name" autocomplete="off"></el-input>
				</el-form-item>

				<el-form-item label="性别"  prop="sex" label-width="150px">
					<el-select v-model="editForm.sex" placeholder="请选择性别">
					<el-option
					v-for="item in sexOptions"
					:key="item.value"
					:label="item.label"
					:value="item.value">
					</el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="电话号码" prop="phone" label-width="150px">
					<el-input v-model="editForm.phone" autocomplete="off"></el-input>
				</el-form-item>

				<el-form-item label="个人介绍" prop="introduction" label-width="150px">
					<el-input 
					type="textarea"
  					:autosize="{ minRows: 2, maxRows: 4}"
					v-model="editForm.introduction" autocomplete="off"></el-input>
				</el-form-item>

				<el-form-item label="教授课程" prop="lesson" label-width="100px">
					<el-input v-model="editForm.lesson" autocomplete="off"></el-input>
				</el-form-item>

				<el-form-item label="课程开始时间"  prop="lessonStartTime" label-width="150px">
					<el-date-picker
					v-model="editForm.lessonStartTime"
					value-format="yyyy-MM-ddTHH:mm:ss.000Z"
					type="datetime"
					placeholder="选择课程开始日期">
					</el-date-picker>
				</el-form-item>

				<el-form-item label="课程结束时间"  prop="lessonEndTime" label-width="150px">
					<el-date-picker
					v-model="editForm.lessonEndTime"
					value-format="yyyy-MM-ddTHH:mm:ss.000Z"
					type="datetime"
					placeholder="选择课程结束日期">
					</el-date-picker>
				</el-form-item>

				<el-form-item label="头像" prop="photo">
				<el-upload
					class="avatar-uploader"
					action="http://localhost:8081/uploadFile"
					:show-file-list="true"
					multiple
					:limit="1"
					:on-success="handleAvatarSuccess"
					:before-upload="beforeAvatarUpload">
					<!-- 构建虚拟路径 -->
					<img v-if="editForm.photo" :src="editForm.photo" :fit="fit" style="width: 100px; height: 100px">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
				</el-form-item>
			

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetForm('editForm')">取 消</el-button>
				<el-button type="primary" @click="submitForm('editForm')">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	var padDate = function (value) {
		return value <10 ? '0' + value:value;
	};
	export default {
		name: "PersonTrain",
		data() {
			return {
				searchForm: {},
				delBtlStatu: true,

				total: 0,
				size: 10,
				current: 1,

				dialogVisible: false,
				editForm: {

				},

				tableData: [],

				editFormRules: {
					name: [
						{required: true, message: '请输入私教姓名', trigger: 'blur'}
					],
					sex: [
						{required: true, message: '请输入性别', trigger: 'blur'}
					],
					phone: [
						{required: true, message: '请输入联系电话', trigger: 'blur'}
					],
					introduction: [
						{required: true, message: '请输入个人介绍', trigger: 'blur'}
					],
					lesson: [
						{required: true, message: '请输入教授课程', trigger: 'blur'}
					],
					lessonStartTime: [
						{required: true, message: '请输入课程开始时间', trigger: 'blur'}
					],
					lessonEndTime: [
						{required: true, message: '请输入课程结束时间', trigger: 'blur'}
					],
				},

				multipleSelection: [],

				roleDialogFormVisible: false,
				defaultProps: {
					children: 'children',
					label: 'name'
				},
				personTrainData:  [],
				treeCheckedKeys: [],
				checkStrictly: true,
				sexOptions: [{
					value: '男',
					label: '男'
					}, {
					value: '女',
					label: '女'
					}
				],

			}
		},
		created() {
			this.getPersonTrainList()
			this.$axios.get("/sys/personTrain/list").then(res => {
				this.personTrainData = res.data.data.records
			})
		},
		methods: {
			toggleSelection(rows) {
				if (rows) {
					rows.forEach(row => {
						this.$refs.multipleTable.toggleRowSelection(row);
					});
				} else {
					this.$refs.multipleTable.clearSelection();
				}
			},
			handleSelectionChange(val) {
				console.log("勾选")
				console.log(val)
				this.multipleSelection = val;

				this.delBtlStatu = val.length == 0
			},

			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.size = val
				this.getPersonTrainList()
			},
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.current = val
				this.getPersonTrainList()
			},

			resetForm(formName) {
				this.$refs[formName].resetFields();
				this.dialogVisible = false
				this.editForm = {}
			},
			handleClose() {
				this.resetForm('editForm')
			},

			getPersonTrainList() {
				this.$axios.get("/sys/personTrain/list", {
					params: {
						personTrainNum: this.searchForm.personTrainNum,
						current: this.current,
						size: this.size
					}
				}).then(res => {
					this.tableData = res.data.data.records
					this.size = res.data.data.size
					this.current = res.data.data.current
					this.total = res.data.data.total
				})
			},

			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.$axios.post('/sys/personTrain/' + (this.editForm.id?'update' : 'save'), this.editForm)
							.then(res => {

								this.$message({
									showClose: true,
									message: '恭喜你，操作成功',
									type: 'success',
									onClose:() => {
										this.getPersonTrainList()
									}
								});

								this.dialogVisible = false
							})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			editHandle(id) {
				this.$axios.get('/sys/personTrain/info/' + id).then(res => {
					this.editForm = res.data.data
					this.dialogVisible = true
				})
			},
			addHandle() {
				this.editForm = {}
				this.dialogVisible = true
			},
			delHandle(id) {

				var ids = []

				if (id) {
					ids.push(id)
				} else {
					this.multipleSelection.forEach(row => {
						ids.push(row.id)
					})
				}

				console.log(ids)

				this.$axios.post("/sys/personTrain/delete", ids).then(res => {
					this.$message({
						showClose: true,
						message: '恭喜你，操作成功',
						type: 'success',
						onClose:() => {
							this.getPersonTrainList()
						}
					});
				})
			},
			
			// 时间格式方法
			formatDateTime(row, column) {
				// 获取单元格数据
				let data = row[column.property]
				if(data == null) {
					return null
				}
				let dt = new Date(data)
				return dt.getFullYear() + '-' + padDate(dt.getMonth() + 1) + '-' + padDate(dt.getDate()) + ' ' + padDate(dt.getHours()) + ':' + padDate(dt.getMinutes()) + ':' + padDate(dt.getSeconds())
			},
			// 日期格式方法
			formatDate(row, column) {
				// 获取单元格数据
				let data = row[column.property]
				if(data == null) {
					return null
				}
				let dt = new Date(data)
				return dt.getFullYear() + '-' + padDate(dt.getMonth() + 1) + '-' + padDate(dt.getDate())
			},


			handleAvatarSuccess(res) {
	          // 把图片名给img
	          this.editForm.photo = "http://localhost:8081/api/file/"+res;
	        },
		    beforeAvatarUpload(file) {
		      // 设置限定格式
		      const img_mimetype = ['image/jpeg','image/jpg','image/png']
		      const isJPG =  img_mimetype.includes(file.type);
		      const isLt2M = file.size / 1024 / 1024 < 2;
		      if (!isJPG) {
		        this.$message.error('上传头像只能是图片格式!');
		        return false;
		      }
		      if (!isLt2M) {
		        this.$message.error('上传头像图片大小不能超过 2MB!');
		        return false;
		      }
		      return isJPG && isLt2M;
		    },
			formatData(row) {
				let rowPerson = (row && row.person) || [];
				let arr = [];
				rowPerson.forEach(item => {
				//如果数据特别多的话,还可以在这里加if判断,仅展示规定的数据
					arr.push(item);
				});
				//
				return arr.join(",");
			}
	

		}
	}
</script>

<style scoped>

	.el-pagination {
		float: right;
		margin-top: 22px;
	}

</style>